package org.example.service.market;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.dao.dao.market.CKindDao;
import org.example.dao.dto.market.CKindDto;
import org.example.dao.entity.market.CKind;
import org.example.skytool.commom.IdWorker;
import org.example.utils.market.Kind.RedisKindService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author xluo
 * @date 2023/11/3 9:34
 */
@Service
public class CKindService {

    @Resource
    private CKindDao cKindDao;

    @Resource
    private IdWorker idWorker;

    @Resource
    private RedisKindService redisKindService;

    /**
     * 添加商品类型
     */
    public CKind addKind(CKind kind){
        Long fatherId = kind.getFatherId();
        kind.setId(idWorker.nextId());
        CKind father = cKindDao.selectById(fatherId);
        if(father == null) {
            kind.setFatherId(0L);
            kind.setLevel(1);
        } else {
            kind.setLevel(father.getLevel() + 1);
        }
        cKindDao.insert(kind);
        return kind;
    }

    /**
     * 删除商品类型
     */
    public void deleteKind(CKind kind){
        kind.setUpdateTime(new Date());
        kind.setIsValid(0);
        cKindDao.updateById(kind);
    }

    /**
     * 修改商品类型
     */
    public CKind updateKind(CKind kind){
        Long fatherId = kind.getFatherId();
        CKind father = cKindDao.selectById(fatherId);
        if(father != null) {
            kind.setLevel(father.getLevel() + 1);
        }
        kind.setUpdateTime(new Date());
        cKindDao.updateById(kind);
        return kind;
    }

    /**
     * 查询商品类型
     */
    public IPage<CKind> selectKind(Long limit, Long start){
        Page<CKind> cKindPage = cKindDao.selectPage(new Page<>(start, limit), new LambdaQueryWrapper<>());
        return cKindPage;
    }

    /**
     * 查询该商店有哪些商品分类(商户)
     */
    public Page<CKindDto> selectKindByStore(Long limit, Long start, Long storeId, Long fatherId) {
        List<CKindDto> kinds = cKindDao.getKinds(storeId, fatherId, (start - 1) * limit, limit);
        Long total = cKindDao.getKindsNum(storeId, fatherId);
        Page<CKindDto> page = new Page<>(start, limit);
        page.setTotal(total);
        page.setRecords(kinds);
        return page;
    }

    /**
     * 查询所有商品分类(管理员)
     */
    public Page<CKindDto> selectAllKind(Long limit, Long start, Long fatherId) {
        List<CKindDto> kinds = cKindDao.getKinds(null, fatherId, (start - 1) * limit, limit);
        Long total = cKindDao.getKindsNum(null, fatherId);
        Page<CKindDto> page = new Page<>(start, limit);
        page.setTotal(total);
        page.setRecords(kinds);
        return page;
    }

}
